//
//  HELCourseCommentVC.m
//  NursingAssociation
//
//  Created by wsj2015 on 2017/2/16.
//  Copyright © 2017年 wsj2015. All rights reserved.
//

#import "HELCourseCommentVC.h"
#import "HCSStarRatingView.h"
#import "HELCommentCell.h"
#import "Masonry.h"
#import "HELCourseCommentModel.h"
#import "WSJPopview.h"
#import "HELCourseContentsVC.h"
@interface HELCourseCommentVC ()
@property (nonatomic,  assign) BOOL isFirstEnty;

@property (nonatomic,  assign) NSUInteger page;
@property (nonatomic,  strong) HCSStarRatingView *ratingView;
@property (nonatomic,  strong) UILabel *commentL;

@property (nonatomic,  assign) BOOL canScroll;


@end

@implementation HELCourseCommentVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(acceptMsg:) name:kGoTopNotificationName object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(acceptMsg:) name:kLeaveTopNotificationName object:nil];//其中一个TAB离开顶部的时候，如果其他几个偏移量不为0的时候，要把他们都置为0
}


-(void)acceptMsg : (NSNotification *)notification{
    //NSLog(@"%@",notification);
    NSString *notificationName = notification.name;
    if ([notificationName isEqualToString:kGoTopNotificationName]) {
        NSDictionary *userInfo = notification.userInfo;
        NSString *canScroll = userInfo[@"canScroll"];
        if ([canScroll isEqualToString:@"1"]) {
            self.canScroll = YES;
            self.tableView.showsVerticalScrollIndicator = YES;
        }
    }else if([notificationName isEqualToString:kLeaveTopNotificationName]){
        self.tableView.contentOffset = CGPointZero;
        self.canScroll = NO;
        self.tableView.showsVerticalScrollIndicator = NO;
    }
}


- (instancetype)init
{
    self = [super init];
    if (self) {
        self.page = 1;
        self.canScroll= YES;
    }
    return self;
}

- (void)configUI_p{
    
    UIView *div =[UIView new];
    div.frame = CGRectMake(0, 0, kScreenWidth, 71);
    div.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:div];
    UITapGestureRecognizer *tap =[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
    [div addGestureRecognizer:tap];
    UILabel *label =[UILabel new];
    label.text  =@"我的评分";
    label.font = [UIFont systemFontOfSize:14];
    [label sizeToFit];
    self.commentL = label;
    [div addSubview:label];
    label.frame = CGRectMake((kScreenWidth - label.bounds.size.width)/2, 10, label.bounds.size.width, label.bounds.size.height);
    
    HCSStarRatingView *ratingView =[[HCSStarRatingView alloc] initWithFrame:CGRectMake((kScreenWidth - 120)/2, 13+ 20, 120, 19)];
    ratingView.emptyStarImage = [UIImage imageNamed:@"灰色"];
    ratingView.halfStarImage = [UIImage imageNamed:@"半灰"];
    ratingView.filledStarImage = [UIImage imageNamed:@"黄色"];
    ratingView.allowsHalfStars = YES;
    ratingView.value = [self.courseDtail.courseScore floatValue] /2;
    [div addSubview:ratingView];
    self.ratingView = ratingView;

    
    UIView *line = [UIView new];
    line.frame = CGRectMake(0, 66, kScreenWidth, 5);
    line.backgroundColor = kTableView_bg;
    [div addSubview:line];
    
   
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.top.equalTo(self.view).offset(71);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    self.tableView.tableFooterView = [UIView new];
    self.tableView.dataVerticalOffset = 70;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:@"HELCommentCell" bundle:nil] forCellReuseIdentifier:@"HELCommentCell"];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 100;
    self.ratingView.userInteractionEnabled = NO;
    weakSelf_define;
    [self.tableView wsj_HeaderRefreshBlock:^{
        [weakSelf reqestData:YES];
    }];
    [self.tableView wsj_FooterRefreshBlock:^{
        [weakSelf reqestData:NO];
    }];
    
    if ([self.courseDtail.courseScore integerValue] == 0) {
        label.text = @"暂未评分";
        
    }else{
        label.text = @"我的评分";
        self.ratingView.value = [self.courseDtail.courseScore floatValue];
       
    }
    
  
}
- (void)tapGesture:(UITapGestureRecognizer *)tap{

    if (![self.courseDtail.status containsString:@"已完成"]) {
        cwqAlertMessage(@"您还未完成课程,不能评分");
        return;
    }
    weakSelf_define;
//    if ([self.courseDtail.courseScore integerValue] == 0) {
        [[WSJPopview sharedWsjPopView] showRatingView:YES withHelpScore:0 withDoneBlock:^(CGFloat help_score, NSString *commet) {
            NSInteger score = [@(help_score) integerValue];
            [weakSelf giveCommetAndScore:commet score:@(score)];
            
        }];
//    }
    
    
    
}





- (void)giveCommetAndScore:(NSString *)comment score:(NSNumber *)score{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"courseId"] = self.courseDtail.id;
    params[@"score"]  =score;
    params[@"commentContent"] = comment;
    cwqHud(self.view);
    weakSelf_define;
    [[HELNetworkManager sharedMg] PUT:kCourseSendCommentAndScore parameters:params progress:nil success:^(id response) {
        [hud hide:YES];
        cwqHudSuccess(@"评分成功~");
        weakSelf.commentL.text = @"我的评分";
        weakSelf.ratingView.value =  [score floatValue] /2;
        [weakSelf reqestData:YES];
        [weakSelf.view layoutIfNeeded];
        
    } failure:^(NSString *err) {
        
        [hud hide:YES];
        
    }];
   
    
 
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (!self.canScroll) {
        [scrollView setContentOffset:CGPointZero];
    }
    CGFloat offsetY = scrollView.contentOffset.y;
    if (offsetY<0) {
        if (!self.isFirstEnty) {
            return;
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:kLeaveTopNotificationName object:nil userInfo:@{@"canScroll":@"1"}];
    }
}

-(void)dealloc{
   
    [[NSNotificationCenter defaultCenter] removeObserver:self];
  
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    
    CGRect frame =   self.tableView.frame;
    frame.size.height -= 64 + 49;
    self.tableView.frame = frame;
    
}

- (void)firstGetData{
    
   
    if (!self.isFirstEnty) {
        [self configUI_p];
        [self.tableView.header beginRefreshing];
         self.isFirstEnty = !self.isFirstEnty;
    }
    
}
- (void)reqestData:(BOOL)isRecover{
    
    
    if (isRecover) {
        self.page = 1;
    }else{
        self.page ++ ;
    }
    
    self.tableView.loading = YES;
    weakSelf_define;
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    params[@"page"] = @(self.page);
    params[@"rows"] = @(10);
    NSString *url = [NSString stringWithFormat:@"%@/%@",kCourseCommentList,self.courseDtail.id];
    [[HELNetworkManager sharedMg] GET:url parameters:params success:^(id responseObject) {
        [weakSelf.tableView.header endRefreshing];
        [weakSelf.tableView.footer endRefreshing];
        weakSelf.tableView.loading = NO;
        if (isRecover) {
            [weakSelf.dataArray removeAllObjects];
        }
        if (responseObject[@"success"] && [responseObject[@"success"] integerValue]) {
            
            NSInteger totalPage = 0;
            if ([responseObject[@"data"][@"totalPage"] isKindOfClass:[NSNull class]]) {
                
            }else{
                totalPage =  [responseObject[@"data"][@"totalPage"] integerValue];
            }
            NSInteger currentPage = [responseObject[@"data"][@"page"] integerValue];
            if (currentPage>=totalPage) {
                [weakSelf.tableView.footer noticeNoMoreData];
            }else{
                [weakSelf.tableView.footer resetNoMoreData];
            }
            
            [weakSelf.dataArray addObjectsFromArray:[HELCourseCommentModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"data"]]];
            [weakSelf.tableView reloadData];
        }
        
        
    } failure:^(NSString *err) {
        [weakSelf.tableView.header endRefreshing];
        [weakSelf.tableView.footer endRefreshing];
        weakSelf.tableView.loading = NO;
        
    }];
    
   
    
    

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    HELCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HELCommentCell"];
    cell.model = self.dataArray[indexPath.row];
    return cell;
    
}

@end
